package com.jmpt.fangbohui.ui;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.NewHouseBean;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.ui.base.BaseViewHolder;
import com.jmpt.fangbohui.ui.holder.SearchHistoryItemHolder;
import com.jmpt.fangbohui.utils.FileUtils;
import com.jmpt.fangbohui.utils.SpUtils;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.jmpt.fangbohui.view.ClearEditText;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class SearchActivity extends BaseActivity  {
	
	public static final String CURR_KEY = "curr_key";

	public static final String SEARCH_HINT = "search_hint";
	
	private final String SP_NAME = "search_list";
	
	@ViewInject(R.id.et_search_key)
	private ClearEditText mEditText;
	
	@ViewInject(R.id.lv_search_history)
	private ListView mListView;
	
	@ViewInject(R.id.tv_search)
	private TextView mSearch;
	
	@OnClick(R.id.btn_search_back)
	public void back(View view){
		setResult(RESULT_CANCELED);
		finish();
	}
	
	private View cleanSearch;
	
	/**
	 * 传进来的key
	 */
	private String mInKey;

	private String mSearchHint;
	
	private Intent intent;
	
	private List<String> searchHistoryList;

	private SearchListAdapter searchListAdapter;
	
	@OnClick(R.id.tv_search)
	public void search(View view){
		String searchKey = mEditText.getText().toString().trim();
		if(TextUtils.isEmpty(mInKey)){ //传进来的当前搜索的key 为空
			if(!TextUtils.isEmpty(searchKey)){
				Intent result = new Intent();
				result.putExtra("search_key", searchKey);
				setResult(RESULT_OK,result);
			}
		}else{//传进来的当前搜索的key 不为空
			if(!mInKey.equals(searchKey)){ //前后不一致
				Intent result = new Intent();
				result.putExtra("search_key", searchKey);
				setResult(RESULT_OK,result);
			}
		}
		
		saveToHistory(searchKey);
		
		finish();
	}
	
	/**
	 * 保存到历史记录
	 */
	private void saveToHistory(String key) {
		// TODO Auto-generated method stub
		if(TextUtils.isEmpty(key) ){
			return;
		}
		
		if(searchHistoryList.contains(key)){
			searchHistoryList.remove(key);
		}
		
		searchHistoryList.add(0,key);
		try {
			FileUtils.write2JsonCache(Constants.SharedPreferences.SEARCH_KEY_LIST, new Gson().toJson(searchHistoryList));
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpUtils.close();
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		
		ViewUtils.inject(this);
		
		initDate();
		
		initView();
		
	}

	private void initDate() {
		intent = getIntent();
		if(intent != null){
			mInKey = intent.getStringExtra(CURR_KEY);
			mSearchHint = intent.getStringExtra(SEARCH_HINT);
		}
		
		String list = FileUtils.readJsonCache(Constants.SharedPreferences.SEARCH_KEY_LIST, "[]");
		
		searchHistoryList = new Gson().fromJson(list, new TypeToken<List<String>>() {}.getType());
		
	}

	private void initView() {
		mEditText.setText(mInKey);
		if(!TextUtils.isEmpty(mSearchHint)){
			mEditText.setHint(mSearchHint);
		}
		mSearch.setText(TextUtils.isEmpty(mInKey) ? "取消" : "搜索");
		mEditText.setSelection(mInKey == null ? 0 : mInKey.length());
		mEditText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				String text = mEditText.getText().toString().trim();
				mSearch.setText(TextUtils.isEmpty(text) ? "取消" : "搜索");
			}
		});

		cleanSearch = View.inflate(UIUtils.getContext(), R.layout.item_search_history_clean, null);
		searchListAdapter = new SearchListAdapter();
		mListView.setAdapter(searchListAdapter);
		notifyListView();
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(searchHistoryList!=null && searchHistoryList.size() > arg2){
					mEditText.setText(searchHistoryList.get(arg2));
					search(null);
				}else{
					if(arg1 == cleanSearch){
						searchHistoryList.clear();
						try {
							FileUtils.write2JsonCache(Constants.SharedPreferences.SEARCH_KEY_LIST, "");
						} catch (Exception e) {
							e.printStackTrace();
						}
						notifyListView();
					}
				}
			}
		});
		
	}
	
	protected void notifyListView() {
		searchListAdapter.notifyDataSetChanged();
		if(searchHistoryList == null || searchHistoryList.size() < 1 ){
			mListView.removeFooterView(cleanSearch);
		}else{
			mListView.addFooterView(cleanSearch);
		}
	}

	class SearchListAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			if(searchHistoryList != null)
				return searchHistoryList.size();
			return 0;
		}

		@Override
		public Object getItem(int position) {
			if(searchHistoryList != null)
				return searchHistoryList.get(position);
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SearchHistoryItemHolder holder;
			if(convertView == null){
				holder = new SearchHistoryItemHolder(mContext);
				convertView = holder.getRootView();
			}else{
				holder = (SearchHistoryItemHolder) convertView.getTag();
			}
			holder.setData(searchHistoryList.get(position));
			return convertView;
		}
		
	}

}
